/**
 * 系统工具类
 */
var Utils = {
		/**
		 * 打印log
		 */
		log: function(obj){
			if(typeof(console) != "undefined" && console != null){
				console.log(obj);
			}
		},
		setWidth: function(w){
			this.width = w;
		},
		/**
		 * 获取页面宽度
		 */
		getWidth: function(){
			return this.width;
		},
		setHeight: function(h){
			this.height = h;
		},
		/**
		 * 获取页面高度
		 */
		getHeight: function(){
			return this.height;
		},
		initPageSize: function(){
			Ext.onReady(function(){
				Utils.getWindowDesimis();
				//监控窗体变化窗台
				window.onresize = function(){
					Utils.getWindowDesimis();
				}
			});
		},
		/**
		 * 获取窗体的大小，分别设置窗体的宽，高
		 */
		getWindowDesimis: function(){
			var width = Ext.getBody().dom.scrollWidth;
			var height = Ext.getBody().dom.scrollHeight;
			if(width  == 0){
				width = document.documentElement.clientWidth;
			}
			if(height == 0){
				height = document.documentElement.clientHeight;
			}
			Utils.setWidth(width);
			Utils.setHeight(height);
		},
		/**
		 * 扩展数组属性，在数组索引的指定位置插入元素
		 * @param index 索引位置
		 * @param item  新元素
		 * @param array 数组元素
		 */
		insertArray: function (index, item, array){
			array.splice(index, 0, item);
		},
		/**
		 * 判断对象是否为json
		 * @param obj
		 * @returns {Boolean}
		 */
		isJson: function(obj){
		    var isjson = typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
		    return isjson;
		},
		/**
		 * 查询数据记录
		 * @param options
		 */
		checkNumber: function(options){
			//配置输参数
			var opts = {
					type: 'model',/*检查方式，model：建模方式，sql：查询方式*/
					objPath: '',/*建模路径*/
					filter: '',/*过滤条件*/
					sql: ''/*sql语句*/
			};
			Ext.apply(opts,options);
			var number = 0;
			return number;
		},
		/**
		 * 数值类型相乘计算
		 */
		multiply: function(num1, num2) {
			   var baseNum, baseNum1, baseNum2;
			   try {
			      baseNum1 = num1.toString().split(".")[1].length;
			   } catch (e) {
			     baseNum1 = 0;
			   }
			   try {
			       baseNum2 = num2.toString().split(".")[1].length;
			   } catch (e) {
			     baseNum2 = 0;
			   }
			   baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
			   var precision = (baseNum1 >= baseNum2) ? baseNum1 : baseNum2;//精度
			   return (num1*num2).toFixed(precision);;
		},
		/**
		 * 生成随机guid
		 */
		getRwid: function () {
            return 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16).toUpperCase();
            });
        },
        /**
         * 判断json对象中是否存在执行的属性
         */
        jsonContaintKey: function(jsonObj,key){
        	return jsonObj.hasOwnProperty(key);
        },
        /**
         * md5加密大写
         */
        md5: function(str){
        	return md5(str).toUpperCase();
        },
        /**
         * 给定的数字前面自动补0
         * @param num给定的数值
         * @param len数值长度
         */
        fillNumberZero:function (num, len) {
            return (num/Math.pow(10,len)).toFixed(len).substr(2);
        },
		/**
		 * 加密字符串
		 */
		encrypt: function(str){
			if(Ext.isEmpty(str)){
				return "";
			}

			var keyHex =CryptoJS.enc.Utf8.parse(Constants.ENCRYPTKEY);
		    var encrypted = CryptoJS.DES.encrypt(str, keyHex, {
		        mode: CryptoJS.mode.ECB,
		        padding: CryptoJS.pad.Pkcs7
		    });
		    return encrypted.toString();
		},
		/**
		 * 解密
		 */
		decrypt: function(str){
			if(Ext.isEmpty(str)){
				return "";
			}

		    var keyHex = CryptoJS.enc.Utf8.parse(Constants.ENCRYPTKEY);
		    var decrypted = CryptoJS.DES.decrypt({
		        ciphertext: CryptoJS.enc.Base64.parse(str)
		    }, keyHex, {
		        mode: CryptoJS.mode.ECB,
		        padding: CryptoJS.pad.Pkcs7
		    });

		    return decrypted.toString(CryptoJS.enc.Utf8);
		},
		/**
		 * 对话框属性
		 */
		dialog:{
			/**
			 * 根据textfield输入的文本框内容，自动模糊匹配出对应记录
			 * @param config 配置信息
			 */
			fillTextFieldGridDialog: function(config){
				var opts = {
						//联想字段
						field: null,
						//业务模型对象路径
						gridObjPath: null,
						//显示宽度，不设置默认为field的宽度
						width: 300,
						//显示高度，默认200的高度
						height: 200,
						//选择记录之后的回调函数，2个参数record->记录值,index:行索引
						call: Ext.emptyFn,
						//查询条件:" and cphm like '%{0}%'",通过format格式化查询条件,替换掉通配符
						filter: null
				};
				Ext.apply(opts,config);
				if(!opts.field){
					Utils.log("无效的field");
					return;
				}
				if(Ext.isEmpty(opts.gridObjPath)){
					Utils.log("无效的gridObjPath");
					return;
				}
				if(Ext.isEmpty(opts.filter)){
					Utils.log("无效的查询条件参数");
					return;
				}
				opts.field.on("change",function(selfField,newValue,oldValue,optsis){
					//声明唯一编码
					var tipsGridPanelId = selfField.tipsGridPanelId || Ext.id();
					//根据唯一编码获取对象
					var tipsGridPanel = Ext.get(tipsGridPanelId);//
					if(tipsGridPanel == null){
						var top = selfField.getHeight()*2;
						var left = selfField.labelWidth+(selfField.labelWidth*0.2);
						var html = '<div id="'+tipsGridPanelId+'" style="position:absolute;z-index:999999;height:'+opts.height+'px;width:'+opts.width+'px;left:'+left+'px;top:'+top+'px;"></div>';
						tipsGridPanel = Ext.DomHelper.append(selfField.getId(),html,true); 
						selfField.tipsGridPanelId = tipsGridPanelId;
						Ext.create('Ext.com.bkfm.datagrid', {
							id: "grid_"+tipsGridPanelId,
							renderTo: tipsGridPanelId,
							objPath : opts.gridObjPath,
							height: opts.height,
							width: opts.width,
							border: true,
							loadAuto: false,
							showstandardBtn: false,
							afterload: function(){
								selfField.focus();
							},
							listeners:{
								itemdblclick: function(grid,record,item,index,e,eOpts){
									Ext.callback(opts.call,this,[record,index]);
									tipsGridPanel.hide();
								}
							},
							tbar:[{
								text: "确定",
								iconCls: "ok",
								handler: function(self){
									var grid = self.ownerCt.ownerCt;
									var record = grid.getSelectedRecord();
									if(record ==null){
										return;
									}
									var index = record.index;
									Ext.callback(opts.call,this,[record,index]);
									tipsGridPanel.hide();
								}
							},'->',{
								text: "关闭",
								iconCls: "close",
								handler: function(){
									tipsGridPanel.hide();
								}
							}]
						});
						
					} 
					var grid = Ext.getCmp("grid_"+tipsGridPanelId);
					tipsGridPanel.show();
					if(grid !=null){
						//var filter = " and cphm like '%"+Ext.util.Format.uppercase(selfField.getValue())+"%'";
						//grid.search(filter);
						//var cls = 'my-class', text = 'Some text';
					   // var s = Ext.String.format('<div class="{0}">{1}</div>', cls, text);
						var filter = Ext.String.format(opts.filter,selfField.getValue());
						grid.search(filter);
					}
				});

			}
		},
		/**
		 * 打开角色窗体
		 */
		showRoleWin: function(callbackFn){
			var grid = Ext.create('Ext.com.bkfm.datagrid', {
				title: "角色",
				id: "role",
				objPath : "ROOT/XTGLPT/JCSJGL/JSXX/BLK_BASE_ROLES",
				border: true,
				orderby : ' ORDER BY ORDER_BY ASC',
				showstandardBtn: false,
		 		tbar:[{
		 			text: '确定',
		 			iconCls: 'ok',
		 			handler: function(){
		 				if(Ext.isFunction(callbackFn)){
		 					var records = grid.getSelectedRecords();
							Ext.callback(callbackFn,this,[records]);
							win.close();
		                }
		 			}
		 		},'-',{
		 			text: '关闭',
		 			iconCls: 'close',
		 			handler: function(){
		 				win.close();
		 			}
		 		},'->',{
		 			text: '高级查询',
					iconCls: 'adsearch',
					handler: function(){
						grid.customizeQuery();
					}
		 		}]
			});
			var win = Ext.create('Ext.com.bkfm.window', {
				title : "角色",
				autoScroll : true,
				modal : true,
				height : Utils.getHeight()*0.7,
				width : Utils.getWidth()*0.6,
				items: [grid]
			});
			win.show();
		},
		/**
		 * 打开用户信息列表
		 * callbackFn: 选中节点后的事件，返回records选中数组,
		 */
		showUserWin: function(callbackFn){
			var grid = Ext.create('Ext.com.bkfm.datagrid', {
				objPath : "ROOT/XTGLPT/JCSJGL/YHXX/BLK_BASE_USERS",
				border: 0,
				frame: false,
				hiddenField: ['USER_PWD'],
				orderby : ' ORDER BY USER_NO ASC',
				showstandardBtn: false,
		 		tbar:[{
		 			text: '确定',
		 			iconCls: 'ok',
		 			handler: function(){
		 				if(Ext.isFunction(callbackFn)){
		 					var records = grid.getSelectedRecords();
							Ext.callback(callbackFn,this,[records]);
							win.close();
		                }
		 			}
		 		},'-',{
		 			text: '关闭',
		 			iconCls: 'close',
		 			handler: function(){
		 				win.close();
		 			}
		 		},'->',{
		 			text: '高级查询',
					iconCls: 'adsearch',
					handler: function(){
						grid.customizeQuery();
					}
		 		}]
			});
			var win = Ext.create('Ext.com.bkfm.window', {
				title : "用户列表",
				autoScroll : true,
				modal : true,
				height : Utils.getHeight()*0.7,
				width : Utils.getWidth()*0.6,
				items: [grid]
			});
			win.show();
		},
		/**
		 * 打开组织架构窗体
		 * callbackFn: 选中节点后的事件，返回records选中数组,
		 */
		showOrgWin: function(callbackFn){
		 	var tree = Ext.create("Ext.com.bkfm.tree",{
		 		rootVisible: true,
		 		rootLabel: "组织",
		 		treeConfigId: "org",
		 		rootTreeId: "00000000000000000000000000000001",
		 		objPath: 'ROOT/XTGLPT/JCSJGL/ZZXX/BLK_BASE_ORGS',
		 		border: false,
		 		autoScroll: true,
		 		checkbox: true,
		 		mappingField:['ORG_ID','ORG_NAME','PARENT_ORG_ID','IS_CHILD_NODE','ORDER_BY'],
		 		tbar:[{
		 			text: '确定',
		 			iconCls: 'ok',
		 			handler: function(){
		 				if(Ext.isFunction(callbackFn)){
		 					var records = tree.getView().getChecked();
							Ext.callback(callbackFn,this,[records]);
							win.close();
		                }
		 			}
		 		},'-',{
		 			text: '关闭',
		 			iconCls: 'close',
		 			handler: function(){
		 				win.close();
		 			}
		 		}]
		 	});
			var win = Ext.create('Ext.com.bkfm.window', {
				title : "组织结构",
				autoScroll : true,
				modal : true,
				height : Utils.getHeight()/2,
				width : Utils.getWidth()/2,
				items: [tree]
			});
			win.show();
		},
		/**
		 * 设置登录用户信息
		 */
		setCurrentUser: function(current_user){
			top.current_user = current_user;
			top.current_user.user_pwd=null;
		},
		/**
		 * 获取登录用户信息
		 */
		getCurrentUser: function(){
			return top.current_user;
		},
		/**
		 * 设置登录用户所有页面的按钮权限
		 */
		setAllPageBtn: function(pageBtnMap){
			top.pageBtnMap = pageBtnMap;
		},
		/**
		 * 获取指定页面所具有的按钮权限
		 */
		getPageBtn: function(page_key){
			if(Ext.isEmpty(page_key)){
				return false;
			}
			var btn_list = top.pageBtnMap[page_key];
			return btn_list;
		},
		/**
		 * 判断用户打开页面是否具有某一按钮权限
		 * @param page_key 页面编码
		 * @param btn_code 按钮编码
		 * 返回true or false
		 */
		hasPageBtnPermis: function(page_key,btn_code){
			if(Ext.isEmpty(page_key)){
				return false;
			}
			var btn_list = top.pageBtnMap[page_key];
			if(Ext.isEmpty(btn_list)){
				return false;
			}
			return Ext.Array.contains(btn_list,btn_code);
		},
		/**
		 * 是否显示页面自定义按钮
		 * false:不隐藏,true:隐藏
		 */
		isHiddenCustomPageBtn: function(btn_code){
			//获取当前页面的rwid
			var page_index = Utils.getReqParams("rwid");
			if(Utils.hasPageBtnPermis(page_index,btn_code)){
				return false;
			}else{
				return true;
			}
		},
		/**
		 * 设置当前登录用户所具有的业务模型按钮权限
		 */
		setAllModelBtn: function(modelBtnMap){
			top.modelBtnMap = modelBtnMap;
		},
		/**
		 * 获取指定业务模型所具有的按钮权限
		 */
		getModelBtn: function(model_path){
			if(Ext.isEmpty(model_path)){
				return false;
			}
			var btn_list = top.modelBtnMap[model_path];
			return btn_list;
		},
		/**
		 * 判断使用的业务模型是否具有指定功能按钮权限
		 * @param model_path 业务模型路径
		 * @param btn_code 按钮编码
		 * 返回true or false
		 */
		hasModelBtnPermis: function(model_path,btn_code){
			if(Ext.isEmpty(model_path)){
				return false;
			}
			var btn_list = top.modelBtnMap[model_path];
			if(Ext.isEmpty(btn_list)){
				return false;
			}
			return Ext.Array.contains(btn_list,btn_code);
		},
		/**
		 * 获取url请求参数
		 * @param key 请求参数名称
		 */
		getReqParams: function(key){
			var args = new Object();
	        var query = location.search.substring(1);
	        var pairs = query.split("&"); // Break at ampersand
	        for (var i = 0; i < pairs.length; i++) {
	            var pos = pairs[i].indexOf('=');
	            if (pos == -1) continue;
	            var argname = pairs[i].substring(0, pos);
	            var value = pairs[i].substring(pos + 1);
	            value = decodeURIComponent(value);
	            args[argname] = value;
	        }
	        return args[key];
		}
}
Utils.initPageSize();
